<style lang='scss'>
#base-info {
  .convert-dialog > .el-dialog {
    width: 1700px;
  }

  .el-textarea.is-disabled .el-textarea__inner,
  .el-input.is-disabled .el-input__inner {
    background-color: #fff;
    border-color: #e4e7ed;
    color: #606266;
    cursor: not-allowed;
  }

  .form-table {
    .el-table__fixed-header-wrapper > table > thead > tr > th > .cell,
    .el-table__header-wrapper > table > thead > tr > th > .cell {
      padding: 10px 0;
      text-align: center;
      font-weight: bold;
    }
  }

  .el-table-column--selection > .cell {
    text-align: center;
  }
  .part {
    border: 1px solid #ccc;
    margin-bottom: 20px;
    background-color: #fff;
    .table-title {
      cursor: pointer;
      padding: 10px;
      display: flex;
      align-items: center;
      background-color: #f5f5f5;
    }
  }
  .mt15 {
    margin-top: 15px;
  }

  .button-box {
    text-align: center;
    padding: 20px;
    background-color: #fff;
  }
}
</style>
<template>
  <div id="base-info">
    <Box>
      <el-form :model="modifyForm" :rules="modifyFormRules" ref="modifyForm" :label-position="'' | LABEL_POSITION">
        <el-table
          v-loading="regionLoading"
          element-loading-spinner="el-icon-loading"
          :data="modifyForm.list"
          border
          class="form-table"
          :max-height="maxHeight"
          @selection-change="handleSelectionChange"
        >
          <el-table-column v-if="type !='view'" type="selection" width="55" class="tc"></el-table-column>
          <el-table-column label="接口描述" min-width="200">
            <template slot-scope="scope">
              <el-form-item :prop=" 'list.' + scope.$index + '.desc' " :rules="modifyFormRules.desc" class="mt15">
                <el-input
                  type="textarea"
                  :readonly="type == 'view'"
                  :autosize="{ minRows: 1, maxRows: 1}"
                  v-model="scope.row.desc"
                  placeholder="请输入描述"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="type" min-width="200">
            <template slot-scope="scope">
              <el-form-item :prop=" 'list.'  + scope.$index + '.type' " :rules="modifyFormRules.type" class="mt15">
                <el-select placeholder="请选择" v-model="scope.row.type">
                  <el-option v-for="item in typeOpts" :key="item" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="apiName" min-width="200">
            <template slot-scope="scope">
              <el-form-item :prop=" 'list.' +scope.$index + '.apiName' " :rules="modifyFormRules.apiName" class="mt15">
                <el-input :readonly="type == 'view'" v-model="scope.row.apiName" placeholder="请输入apiName"></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="routerName" min-width="200">
            <template slot-scope="scope">
              <el-form-item :prop=" 'list.' +scope.$index + '.routerName' " :rules="modifyFormRules.routerName" class="mt15">
                <el-input :readonly="type == 'view'" v-model="scope.row.routerName" placeholder="请输入routerName"></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="serverUrl" min-width="200">
            <template slot-scope="scope">
              <el-form-item :prop=" 'list.' +scope.$index + '.serverUrl' " :rules="modifyFormRules.serverUrl" class="mt15">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 1, maxRows: 1}"
                  :readonly="type == 'view'"
                  v-model="scope.row.serverUrl"
                  placeholder="请输入serverUrl"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>

        <el-row v-if="type != 'view'">
          <el-col :span="24" class="button-box">
            <el-button type="success" @click="addItem({key:'list'})">新增Item</el-button>
            <el-button type="warning" :disabled="selection.length == 0" @click="delItem({key:'list',findKey:'apiName'})">删除Item</el-button>
          </el-col>
        </el-row>
      </el-form>

      <el-row>
        <el-col :span="24" class="button-box">
          <el-button type="primary" @click="onSubmitForm">{{type == 'view' ? '编辑' : '保存'}}</el-button>
          <el-button type="danger" v-if=" type != 'view' " @click="onDelRecord">删除</el-button>
          <el-button @click="modifyDialogVisible = false;">返回</el-button>
        </el-col>
      </el-row>
    </Box>
  </div>
</template>
<script>
import { mapGetters, mapActions, mapState, mapMutations } from "vuex";
import storage from "src/utils/storage";
import { sendReq, tableExportExcel, isJSON,GetQueryString } from "src/utils/tools";

export default {
  data() {
    const pagePermissionsMenu = storage.get("pagePermissionsMenu")
      ? storage.get("pagePermissionsMenu")
      : {};

    const inputWarning = (msg) => {

      return [
        {
          required: true,
          message: msg,
          trigger: "blur,change",
        }
      ];
    };
    let checkEmpty = (obj) => {

      return (rule, value, callback) => {


        if (value != undefined) {
          return callback(new Error(obj.msg));
        } else {
          callback();
        }
      };
    };
    let validateEmpty = (obj) => ([{ required: true, validator: checkEmpty(obj), trigger: 'blur' }]);

    return {
      type: 'view',
      maxHeight: document.documentElement.clientHeight - 60 - 58 - 60 - 30,
      typeOpts: ['requestConfigs', 'onsConfigs'],

      modifyForm: {
        productCode: '',
        list: [{
          desc: '',
          type: '',
          apiName: '',
          routerName: '',
          serverUrl: '',
        }],
      },
      modifyFormRules: {
        // desc: inputWarning('请输入描述'),
        type: inputWarning('请选择类型'),
        apiName: inputWarning('请输入接口名称'),
        routerName: inputWarning('请输入路由器名称'),
        serverUrl: inputWarning('请输入服务器地址'),
      },
      selection: [],
    };
  },
  components: {

  },
  computed: {
    ...mapGetters(["pagination", "regionLoading"])
  },
  watch: {},
  created() {

  },
  mounted() {
    this.onSearch();
  },
  methods: {
    ...mapActions([""]),
    onSearch() {
      sendReq({
        url: '/config/getCommonConfig',
        params: { type: 'halo', productCode: this.$route.params.productCode },
        cb: (data) => {
          if (!data) { return; }

          this.modifyForm.path = data.path;
          this.modifyForm.name = data.name;
          this.modifyForm.zkConfigTypeEnum = data.zkConfigTypeEnum;

          this.modifyForm.list = [];
          let content = data && data.content ? data.content : {};
          for (let key in content) {
            if (key != 'productCode') {
              content[key].forEach((item) => {
                this.modifyForm.list.push({ desc: '', type: key, ...item });
              })
            } else {
              this.modifyForm.productCode = content[key];
            }
          }
          this.modifyForm.list.forEach(e => {
            e.editStatus = false
          })

        }
      })
    },
    handleSelectionChange(selection) {
      this.selection = selection;
      // console.log(selection);
    },
    addItem(obj) {
      // console.log(key);
      this.modifyForm[obj.key].unshift({
        desc: '',
        type: '',
        apiName: '',
        routerName: '',
        serverUrl: '',
      })
    },
    delItem(obj) {
      this.$confirm("确定要删除这条记录吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.selection.forEach((item, index) => {
          for (var i = 0, len = this.modifyForm[obj.key].length; i < len; i++) {
            if (this.modifyForm[obj.key][i][obj.findKey] == item[obj.findKey]) {
              this.modifyForm[obj.key].splice(i, 1);
              break;
            }
          }
        })
      })
    },
    //新增&&编辑保存
    onSubmitForm() {

      if (this.type == 'view') {
        this.type = 'edit';
        return;
      }

      let params = {
        type: this.type,
      };

      this.$refs.modifyForm.validate(valid => {
        if (valid) {

          this.$confirm("确定要提交数据吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {

            let submitData = {
              path: '',
              content: {},
            };
            submitData.path = this.modifyForm.path;
            submitData.name = this.modifyForm.name;
            submitData.zkConfigTypeEnum = this.modifyForm.zkConfigTypeEnum;
            submitData.productCode = this.modifyForm.productCode || this.$route.params.productCode;
            this.typeOpts.forEach((item) => {
              submitData.content[item] = [];
            })
            this.modifyForm.list.forEach((item) => {
              let { desc, apiName, routerName, serverUrl } = item;
              submitData.content[item.type].push({ desc, apiName, routerName, serverUrl });
            })
            sendReq({
              url: '/config/updateNode',
              params: submitData,
              note: true,
              cb: (data) => {
                this.onSearch();
              }
            })


          })

        } else {
          this.$message({
            type: "warning",
            message: "请检查表单必填项!"
          });
        }
      });
    },
    // 删除
    onDelRecord(params) {

      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        sendReq({
          url: '/config/deleteNode',
          params: { path: this.modifyForm.path },
          note: true,
          cb: (data) => {
            this.onSearch();
          }
        })


      })

    },
  }
};
</script>
